package staticresource

import (
	"dub/common"
	"dub/config"
	"dub/define"
	"dub/define/grpcmodel"
	"dub/frame"
	"dub/utils"
	"fmt"
	"github.com/golang/protobuf/proto"
	"net/http"
	"os"
)

type WebStaticResourceServer struct {
	wsrCfg  define.WebStaticReourceServerConfig //用户的微服务配置
	logCfg  define.LogConfig                    //日志配置
	regConn common.IConnector                   //与注册服务器连接
	log     *utils.Logger                       //日志对象
}

func (w *WebStaticResourceServer) Init(cfgPath string) {
	//读取配置
	var err error
	w.wsrCfg, w.logCfg, err = config.GetWebStaticReourceServerConfig(cfgPath)
	if err != nil {
		fmt.Println(err)
		os.Exit(2)
	}

	//日志配置
	log := utils.NewLogger()
	log.SetConfig(w.logCfg)
	w.log = log

	//连接主服务器
	conn := frame.NewConnector()
	conn.CallBack = w.RegServiceCallBack
	w.regConn = conn
	err = w.regConn.Start(w.wsrCfg.RegAddr)
	if err != nil {
		log.Errorf("server.go Init method w.regCon.Start err %v\n", err)
		os.Exit(2)
	}
	w.Reg()
	log.Infof("reg %s server is %s", w.logCfg.DeviceName, w.wsrCfg.Addr)

	// http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(w.wsrCfg.WebWiew))))

	http.Handle("/", http.FileServer(http.Dir(w.wsrCfg.WebWiew)))
	err = http.ListenAndServe(w.wsrCfg.Addr, nil)
	if err != nil {
		w.log.Errorf("server.go Init method start web gate server err %v\n", err)
	}
	w.log.Infoln("web staticresource server start")
}

func index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello golang http!")
}

func (w *WebStaticResourceServer) Reg() {
	serverInfo := &grpcmodel.ModelRegReqServerType{
		Addr:       w.wsrCfg.Addr,
		ServerName: define.ServerNameWeb_StaticResourceServer,
		ServerType: 2,
		ProxyUrl:   w.wsrCfg.ProxyUrl,
	}

	for {
		data, err := proto.Marshal(serverInfo)
		if err != nil {
			w.log.Errorf("server.go reg method proto.Marshal(serverInfo) err %v\n", err)
			continue
		}
		//发送注册命令
		err = w.regConn.Send(define.CmdRegServer_Register, define.CmdSubRegServer_Register_Reg, data)
		if err != nil {
			w.log.Errorf("server.go reg method w.regConn.Send(define.CmdRegServer_Register %d, define.CmdSubRegServer_Register_Reg %d, data) err %v\n", define.CmdRegServer_Register, define.CmdSubRegServer_Register_Reg, err)
			continue
		}
		break
	}
}

func (w *WebStaticResourceServer) RegServiceCallBack(mainId, subId uint16, data []byte) bool {
	if mainId == define.CmdRegServer_Register {
		switch subId {
		case define.CmdSubRegServer_Register_Reg:
			res := &grpcmodel.ModelRegResServerType{}
			err := proto.Unmarshal(data, res)
			if err != nil {
				w.log.Errorf("server.go RegServiceCallBack(%d, %d, data []byte) proto.Unmarshal(data,res) err %v\n", mainId, subId, err)
				return true
			}

			if res.Err == 0 {
				w.log.Infoln("service web staticresource server reg success")
			} else {
				w.log.Infoln("service web staticresource server reg fail")
			}
		}
	}
	return true
}

var webStaticResource *WebStaticResourceServer

func NewWebStaticResourceServer() *WebStaticResourceServer {
	if webStaticResource == nil {
		webStaticResource = new(WebStaticResourceServer)
	}
	return webStaticResource
}
